<template>
  <div class="app-container">
    <!-- stat summary  start -->
    <el-card shadow="always" style="margin-bottom: 16px">
      <el-row :gutter="20">
        <!-- 卡片1 -->
        <el-col :span="6">
          <div class="stat">
            <div class="stat-header">用户数量</div>
            <div class="stat-body">
              <div class="icons">
                <el-icon>
                  <UserFilled />
                </el-icon>
              </div>
              <div class="text">
                <el-tooltip effect="light" content="启用/总数" placement="top-end">
                  {{ statSummay?.userSummary?.enabledNumber }}/{{ statSummay?.userSummary?.total }}
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 卡片2-->
        <el-col :span="6">
          <div class="stat" style="background-color: #67c23a">
            <div class="stat-header">项目数量</div>
            <div class="stat-body">
              <div class="icons">
                <svg-icon name="project" />
              </div>
              <div class="text">
                <el-tooltip effect="light" content="启用/关闭/总数" placement="top-end">
                  {{ statSummay?.projectSummary?.notClosedNumber }}/{{ statSummay?.projectSummary?.closedNumber }}/{{
                    statSummay?.projectSummary?.total
                  }}
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 卡片3-->
        <el-col :span="6">
          <div class="stat" style="background-color: #e6a23c">
            <div class="stat-header">日报数量</div>
            <div class="stat-body">
              <div class="icons">
                <svg-icon name="report" />
              </div>
              <div class="text">
                <el-tooltip effect="light" content="本周/本月/总数" placement="top-end">
                  {{ statSummay?.reportSummary?.weeklyNumber }}/{{ statSummay?.reportSummary?.monthlyNumber }}/{{
                    statSummay?.reportSummary?.total
                  }}
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 卡片4-->
        <el-col :span="6">
          <div class="stat" style="background-color: #f56c6c">
            <div class="stat-header">jira数量</div>
            <div class="stat-body">
              <div class="icons">
                <svg-icon name="Jira" />
              </div>
              <div class="text">
                <el-tooltip effect="light" content="总数" placement="top-end">
                  {{ statSummay?.jiraSummary?.total }}
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- stat summary  end -->

    <!-- 工时填报率 -->
    <el-card shadow="hover" style="margin-bottom: 16px" header="日报填报率">
      <template #header>
        <div style="font-size: 1.2em">
          <el-switch
            v-model="isYesterday"
            inline-prompt
            @change="handleSwitchFilling"
            active-text="昨日"
            inactive-text="今日"
            :active-value="-1"
            :inactive-value="0"
          />

          日报填报率
        </div>
      </template>
      <div style="display: flex; justify-content: space-between">
        <div>
          <el-button-group>
            <el-button plain :icon="Edit" size="small">应填</el-button>
            <el-button size="small" type="primary"> {{ fillingData?.num }}人 </el-button>
          </el-button-group>
          <el-divider direction="vertical" />
          <el-button-group>
            <el-button plain :icon="Check" size="small">已填</el-button>
            <el-button type="success" size="small"> {{ fillingData?.filledNum }}人 </el-button>
          </el-button-group>
          <el-divider direction="vertical" />

          <el-button-group>
            <el-button plain :icon="Close" size="small">未填</el-button>
            <el-button type="info" size="small"> {{ fillingData?.unfilledNum }} 人 </el-button>
          </el-button-group>
          <el-divider direction="vertical" />
          <el-button-group>
            <el-button plain :icon="Paperclip" size="small">填报率</el-button>
            <el-button type="danger" size="small">
              {{ fillingData?.rate }}
            </el-button>
          </el-button-group>
        </div>
        <div>
          <el-button type="primary" @click="toFilling">查看详细</el-button>
        </div>
      </div>
    </el-card>

    <el-card style="min-width: 480px">
      <template #header>
        <div class="card-header" style="height: 30px">
          <el-form :inline="true" style="margin: 0 auto">
            <el-form-item>
              <el-switch
                v-model="isWeek"
                inline-prompt
                @change="handleSwitch"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="按周统计"
                inactive-text="按月统计"
              />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="weekLookup.startDate"
                type="date"
                placeholder="周一"
                size="small"
                style="max-width: 120px"
                @change="handleDate"
              />
              <el-text type="primary" size="small" style="margin: 0 5px">至</el-text>
              <el-date-picker
                v-model="weekLookup.endDate"
                type="date"
                placeholder="周日"
                size="small"
                style="max-width: 120px"
                @change="handleDate"
              />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <div style="width: 100%; min-height: 500px" ref="weekStatRef" />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue"
import dayjs from "dayjs"
import { useRouter } from "vue-router"
import { statSummaryApi, weekBarApi } from "@/api/main"
import { type StatSummary, type EchartsSimpleLine, type WeekLookupRequestData } from "@/api/main/types/main"
import { ElButton, ElDatePicker } from "element-plus"
import { getFillingDataApi } from "@/api/charts"
import { type DayReportFillingSummaryData } from "@/api/charts/types/charts"
import { Paperclip, Close, Check, Edit } from "@element-plus/icons-vue"
import * as echarts from "echarts"
import isoWeek from "dayjs/plugin/isoWeek"
import { getDateByOffset } from "@/utils/common"

// 扩展 dayjs 插件  让一周从周一开始
dayjs.extend(isoWeek)

const router = useRouter()
const weekStatRef = ref(null)
//概况统计 响应
const statSummay = ref<StatSummary | null>(null)
//周工时统计 响应
const weekStat = ref<EchartsSimpleLine | null>(null)
// 人员周工时统计查询条件
const weekLookup: WeekLookupRequestData = reactive({
  startDate: "",
  endDate: ""
})
const today = (): string => {
  return dayjs().format("YYYY-MM-DD")
}

const getStatSummayData = () => {
  statSummaryApi()
    .then(({ data }) => {
      statSummay.value = data
    })
    .catch(() => {
      statSummay.value = null
    })
}
//#region 日报填报率

//  今日/昨天填报率切换
const isYesterday = ref(-1)

const handleSwitchFilling = () => {
  getFillingData()
}

const fillingData = ref<DayReportFillingSummaryData>()
const getFillingData = () => {
  const date = getDateByOffset(isYesterday.value)
  console.log("get filling data", date)
  console.log("today:", today())
  getFillingDataApi(date)
    .then(({ data }) => {
      fillingData.value = data
    })
    .catch(() => {
      fillingData.value = undefined
    })
}
const toFilling = () => {
  router.push({
    name: "Filling",
    query: {
      date: new Date().getTime()
    }
  })
}
//#endregion

const getStatWeek = () => {
  weekBarApi(weekLookup)
    .then(({ data }) => {
      weekStat.value = data
      weekStatChartsInit()
    })
    .catch(() => {
      console.log("getStatWeek error")
      weekStat.value = null
    })
}

// 选择某一周/月
const isWeek = ref(true)

const handleSwitch = () => {
  handleDate(new Date())
}
const handleDate = (val: Date) => {
  // 获取选中的日期
  const selectedDate = dayjs(val)
  if (isWeek.value) {
    // 计算当前选择日期所在周的周一和周日
    const startOfWeek = selectedDate.startOf("isoWeek") // 获取周一
    const endOfWeek = selectedDate.endOf("isoWeek") // 获取周日
    // 设置开始日期和结束日期
    weekLookup.startDate = startOfWeek.format("YYYY-MM-DD")
    weekLookup.endDate = endOfWeek.format("YYYY-MM-DD")
  } else {
    // 计算当前选择日期所在月的第一天和最后一天
    const startOfMonth = selectedDate.startOf("month") // 获取该月的1号
    const endOfMonth = selectedDate.endOf("month") // 获取该月的最后一天

    // 设置开始日期和结束日期
    weekLookup.startDate = startOfMonth.format("YYYY-MM-DD")
    weekLookup.endDate = endOfMonth.format("YYYY-MM-DD")
  }
  getStatWeek()
}

// 初始化周/月工时 柱状图
const weekStatChartsInit = () => {
  if (!weekStat.value) return

  const weekStatDom = weekStatRef.value

  if (!weekStatDom) return

  const weekStatChart = echarts.init(weekStatDom)
  const scope = isWeek.value ? "周" : "月"
  //折线图改为柱状图
  const option = {
    title: {
      text: "实时统计人员 [" + scope + "] 工时(人天)柱状图:" + weekStat.value.xAxisData.length + "人"
    },
    tooltip: {
      formatter: function (params: any) {
        let tooltipContent = params.name + " " + params.value + "<br/>" // 柱状图对应的名称
        tooltipContent += weekStat.value?.otherInfo[params.dataIndex] // 自定义信息，params[0].value 可以根据需要获取
        return tooltipContent
      }
    },
    xAxis: {
      type: "category",
      axisLabel: {
        interval: 0, //代表显示所有x轴标签显示
        rotate: -45 //代表逆时针旋转45度
      },
      data: weekStat.value.xAxisData
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        data: weekStat.value.seriesData,
        type: "bar",
        showBackground: true,
        barMaxWidth: 30,
        backgroundStyle: {
          color: "rgba(180, 180, 180, 0.2)"
        }
      }
    ]
  }
  weekStatChart.setOption(option)
}

onMounted(() => {
  getStatSummayData()
  handleSwitch()
  getFillingData()
})
</script>

<style lang="scss" scoped>
.stat {
  width: 100%;
  background-color: #409eff;
  /* 修改背景色 */
  border-radius: 10px;
  padding: 5px;
  min-height: 80px;
  color: white;
  /* 设置卡片内的文字颜色为白色 */
}

.stat-header {
  margin-top: 5px;
  margin-left: 10px;
  font-size: 18px;
  display: inline-block;
  /* 限制下划线宽度仅与文字匹配 */
  border-bottom: 1px solid white;
  /* 下划线 */
  padding-bottom: 2px;
  /* 设置文字与下划线的间距 */
}

.stat-body {
  display: flex;
  justify-content: space-between;
  /* 左右分布 */
  align-items: center;
  /* 垂直居中 */
  margin: 10px;
}

.icons {
  display: flex;
  align-items: center;
  /* 确保图标垂直居中 */
  font-size: 24px;
  /* 调整图标大小（可选） */
}

.text {
  font-size: 18px;
  /* 调整文本大小（可选） */
}

.card-header {
  padding: 0 auto;
  height: 50px;
}
</style>
